<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Comment extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'customer_id',
        'product_id',
        'content',
        'score',
        'level',
        'has_images',
        'detail',
        'order_id',
        'order_item_id',
    ];

    protected $casts = [
        'detail' => 'json',
    ];

    public function scopeFilter(Builder $builder, $data)
    {

        $page = $data['page'] ?? 1;
        $limit = $data['limit'] ?? 10;

        $skip = ($page - 1) * $limit;

        switch ($data['filter'] ?? null) {
            case '0':
                $builder->latest('score');
                break;
            case '1':
                $builder->latest('id');
                break;
            case '2':
                $builder->where('level', 0)->latest('id');
                break;
            case '3':
                $builder->where('level', 1)->latest('id');
                break;
            case '4':
                $builder->where('has_images', 1)->latest('score');
                break;
            default:
                break;
        }

        return $builder->skip($skip)->limit($limit);

    }

    public function customer()
    {
        return $this->belongsTo(Customer::class);
    }

    public function product()
    {
        return $this->belongsTo(Product::class);
    }

    public function order()
    {
        return $this->belongsTo(Order::class);
    }
}
